<template>
	<cl-dialog ref="dialog" title="编辑信息" width="400px" :visible.sync="visible" @close="close" :props="{
		appendToBody: true,
		closeOnClickModal: false,
		top: '10vh',
		customClass: 'appoint-board__dialog',
		'append-to-body': true,
		'close-on-click-modal': false,
		'close-on-press-escape': false
	}">
		<el-form ref="form" label-position="top" :model="form" :rules="rules">
			<el-form-item>
				<el-card shadow="never">
					<el-row >
						<el-col :span="24" v-if="compileType === '事业部'">
							<el-form-item label="所属事业部" required>
								<el-input v-model="detail.biz_name" disabled />
							</el-form-item>
						</el-col>
						<el-col :span="24" v-if="compileType === '所属品牌'"  v-auth="'store_editcustomer_bra_watime'" >
							<el-form-item label="所属品牌" required>
								<cl-select v-model="form.bra_id" placeholder="请选择品牌" filterable style="width: 100%">
									<el-option v-for="item in bizRefData.brand" :key="item.bra_id"
										:label="item.bra_name" :value="item.bra_id" />
								</cl-select>
							</el-form-item>
						</el-col>
						<el-col :span="24" v-if="bizRefData.shop_childs.length > 0 && compileType === '所属门店'">
							<el-form-item label="所属门店" prop="dept_id">
								<cl-shop-select v-model="form.dept_id" filterable placeholder="请选择所属门店"
									style="width: 100%" :biz_id="form.biz_id" />
							</el-form-item>
						</el-col>
						<el-col :span="24" v-if="compileType === '客户名称'">
							<el-form-item label="客户名称" prop="cus_name">
								<el-input placeholder="请填写客户名称" v-model="form.cus_name" maxlength="12" />
							</el-form-item>
						</el-col>
						<el-col :span="24" v-if="compileType === '客户微信号'">
							<el-form-item label="客户微信号" prop="cus_wx">
								<el-input placeholder="请填写客户微信号" v-model.trim="form.cus_wx" maxlength="30" />
							</el-form-item>
						</el-col>
						<el-col :span="24" v-if="compileType === '客户手机号'">
							<el-form-item label="客户手机号" prop="cus_mobile">
								<el-input placeholder="请填写客户手机号" v-model.trim="form.cus_mobile" maxlength="11" />
							</el-form-item>
						</el-col>
						<el-col :span="24" v-if="compileType==='加微时间'" v-auth="'store_editcustomer_bra_watime'">
							<el-form-item label="加微时间" prop="wechat_join_day">
								<cl-date-picker v-model="form.wechat_join_day" placeholder="选择日期" style="width: 100%"
									value-format="yyyy-MM-dd" disabled />
							</el-form-item>
						</el-col>
						<!-- <el-col :span="12">
							<el-form-item label="转介绍" prop="cus_type">
								<cl-select
									v-model="form.cus_type"
									placeholder="请选择转介绍"
									style="width: 100%"
								>
									<el-option label="无转介绍" :value="0" />
									<el-option label="门店转介绍" :value="4" />
								</cl-select>
							</el-form-item>
						</el-col> -->
						<el-col :span="24" v-if="compileType === '加微方式'">
							<el-form-item label="加微方式" prop="id_join_type">
								<cl-select v-model="form.id_join_type" disabled placeholder="请选择加微方式"
									style="width: 100%">
									<el-option v-for="(item, index) in wxJoinTypeList" :key="index" :label="item.label"
										:value="item.value" />
								</cl-select>
							</el-form-item>
						</el-col>
						<el-col :span="24" v-if="form.id_join_type == 99 && compileType === '来源渠道'">
							<el-form-item label="来源渠道" prop="source_id">
								<cl-select v-model="form.source_id" disabled placeholder="请选择来源渠道" style="width: 100%">
									<el-option v-for="(item, index) in sourceList" :key="index" :label="item.cname"
										:value="item.id" />
								</cl-select>
							</el-form-item>
						</el-col>
						<el-col :span="24" v-if="compileType === '会员等级'">
							<el-form-item label="会员等级" prop="cus_grade">
								<cl-select v-model="form.cus_grade" placeholder="请选择会员等级" style="width: 100%">
									<el-option v-for="(item, index) in bizRefData.level" :key="index"
										:label="item.cl_name" :value="item.cl_id" />
								</cl-select>
							</el-form-item>
						</el-col>
						<el-col :span="24" v-if="compileType === '会员性别'">
							<el-form-item label="会员性别" prop="cus_sex" required>
								<el-radio-group v-model="form.cus_sex">
									<el-radio :label="2">女</el-radio>
									<el-radio :label="1">男</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :span="24" v-if="compileType === '会员生日'">
							<el-form-item label="会员生日">
								<cl-date-picker v-model="form.cus_birthday" value-format="yyyy-MM-dd" placeholder="选择日期"
									style="width: 100%" />
							</el-form-item>
						</el-col>
						<el-col :span="24" v-if="compileType === '所在地区'">
							<el-form-item label="所在地区" prop="area">
								<cl-cascader v-model="form.area" :options="addressLevel" placeholder="请选择省市区"
									style="width: 100%" filterable />
							</el-form-item>
						</el-col>
						<el-col :span="24" v-if="compileType === '详细地址'">
							<el-form-item label="详细地址" prop="cus_addr">
								<el-input placeholder="请填写详细地址" v-model="form.cus_addr" />
							</el-form-item>
						</el-col>
						<el-col :span="24" v-if="compileType === '所属部门'">
							<el-form-item label="所属部门" prop="name_ascr_dept">
								<cl-cascader style="width: 100%" clearable :key="0" v-model="form.name_ascr_dept"
									:options="deptList" :props="{
										checkStrictly: false,
										value: 'dept_name',
										label: 'dept_name'
									}" filterable @change="ascrDeptChange" />
							</el-form-item>
						</el-col>
					</el-row>
				</el-card>
			</el-form-item>

			<!--<el-form-item label="会员标签（最多只能选择5个）">
				 <el-card shadow="never">
					<el-row type="flex" justify="center">
						<el-transfer
							ref="tags"
							v-model="form.tag_name"
							filterable
							:data="tagList"
							:titles="['标签', '已选']"
							:props="{
								key: 'id',
								label: 'tname'
							}"
						/>
					</el-row>
				</el-card>
				<el-select
					class="tag-wrap"
					placeholder="请选择会员标签"
					v-model="form.tag_name"
					:multiple-limit="5"
					filterable
					multiple
				>
					<el-option
						v-for="item in tagList"
						:key="item.id"
						:label="item.tname"
						:value="item.id"
					/>
				</el-select>
			</el-form-item>

			<el-form-item label="会员备注" prop="add_remarks">
				<el-input
					v-model="form.add_remarks"
					placeholder="请填写会员备注"
					type="textarea"
					:rows="3"
				/>
			</el-form-item>-->
		</el-form>
		<template #footer>
			<el-button @click="close">关闭</el-button>
			<el-button type="primary" :loading="saving" @click="submit">确定</el-button>
		</template>
	</cl-dialog>
</template>
<script>
	import dayjs from "dayjs";
	import { validate } from "@/utils/validate";
	import constant from "@/constant";
	import threeLevel from "@/assets/countryLevel3";
	import { delEmptyChildren } from "@/utils";
	export default {
		props: {
			detail: {
				type: Object,
				default: () => ({})
			}
		},
		data() {
			const validateMobile = (rule, value, callback) => {
				if (!this.isEditMobile) {
					return callback();
				}
				if (!validate.mobile.test(value)) {
					return callback(new Error("客户手机号格式不正确"));
				}
				return callback();
			};
			const validateWx = (rule, value, callback) => {
				if (!this.isEditWx) {
					return callback();
				}
				let len = value.length;
				if (len < 6 || len > 30) {
					// return callback(new Error("微信号6-30个字数"));
				}
				if (!validate.wechat.test(value)) {
					// return callback(new Error("格式为字母、下划线或减号，以字母开头"));
				}
				return callback();
			};
			return {
				saving: false,
				visible: false,
				compileType: "",
				deptList: [],
				addressLevel: threeLevel,
				wxJoinTypeList: constant.WX_JOIN_TYPE,
				pickerOptions: {
					disabledDate(time) {
						let now = dayjs();
						let date = dayjs(time);
						return date.isBefore(now.subtract(2, "day")) || date.isAfter(now);
					}
				},
				visitTypeList: [
					{ label: "回访", value: 0 },
					{ label: "客诉", value: 1 },
					{ label: "退定金", value: 2 },
					{ label: "未处理", value: 3 },
					{ label: "待沟通", value: 4 }
				],
				followTypes: [
					{ label: "电话", value: 1 },
					{ label: "QQ", value: 2 },
					{ label: "微信", value: 3 },
					{ label: "面聊", value: 4 }
				],
				shopList: [],
				sourceList: [],
				form: {
					biz_id: 0,
					bra_id: "",
					dept_id: "",
					cus_name: "",
					cus_mobile: "",
					source_id: "",
					channel_id: "",
					cus_grade: 0,
					cus_sex: 2,
					add_remarks: "",
					cus_area: "",
					cus_addr: "",
					cus_birthday: "",
					cus_type: "",
					wechat_join_day: "",
					cus_wx: "",
					id_join_type: "",
					tag_name: [],
					area: []
				},
				rules: {
					dept_id: [{ required: true, message: "请选择门店" }],
					cus_name: [{ required: true, message: "请填写客户名称" }],
					cus_wx: [
						{ required: true, message: "请填写客户微信号" },
						{ validator: validateWx }
						// {
						// 	pattern: validate.wechat,
						// 	message: "格式为字母、下划线或减号，以字母开头"
						// }
					],
					cus_mobile: [
						// { required: true, message: "请输入新手机号" },
						{ validator: validateMobile }
						// { pattern: validate.mobile, message: "客户手机号格式不正确" }
					],
					// tag_name: [{ required: true, message: "请选择会员标签" }],
					wechat_join_day: [{ required: true, message: "请选择加微日期" }],
					id_join_type: [{ required: true, message: "请选择加微类型" }],
					biz_id: [{ required: true, message: "请选择事业部" }],
					source_id: [{ required: true, message: "请选择来源渠道" }],
					cus_grade: [{ required: true, message: "请选择会员等级" }],
					cus_type: [{ required: true, message: "请选择转介绍" }]
				},
				brandList: [], //品牌
				tagList: []
			};
		},
		computed: {
			isEditMobile() {
				return this.detail.cus_mobile !== this.form.cus_mobile;
			},
			isEditWx() {
				return this.detail.base_wx !== this.form.cus_wx;
			},
			bizRefData() {
				const { biz_id } = this.detail;
				return this.getBizRefData(biz_id);
			}
		},
		methods: {
			open(obj) {
				this.visible = true;
				// this.$refs.drawer.create();
				if (this.detail.dept_id == 0) {
					this.detail.dept_id = "";
				}

				const { tag_name } = this.detail;
				if (tag_name.length) {
					this.detail.tag_name = tag_name.map((e) => e.id);
				}
				Object.keys(this.form).forEach((key) => {
					this.form[key] = this.detail[key] ?? "";
				});

				const { base_wx, biz_id, info, remarks, cus_area } = this.detail;
				this.form.cus_wx = base_wx;
				// this.form.cus_type = info == 4 ? 4 : 0;
				this.form.add_remarks = remarks;
				try {
					this.form.area = JSON.parse(cus_area) || [];
					// this.form.area = (this.detail.cus_area || "").split(",");
				} catch (error) {
					this.form.area = (cus_area || "").split(",").filter((v) => v != "");
				}
				console.log("bra_id", this.form.bra_id);
				this.compileType = obj.type;
				this.form[obj.name] = obj.value;
				console.log(this.form);

				this.init();
				this.getLevelList();
				this.getDeptList();
			},
			async init() {
				const { biz_id } = this.detail;
				this.getBizRefBrand(biz_id);
				this.getBizRefShop(biz_id);
				this.getTagList();
				this.getSource();
			},
			reset() {
				this.$refs.form.resetFields();
			},
			close() {
				// this.$refs.drawer.close();
				this.visible = false;
			},
			//所属部门值改变
			ascrDeptChange(value) {
				console.log(value);
				this.form.name_ascr_dept = value[value.length - 1];
			},
			submit() {
				this.$refs.form.validate(async (valid, errors) => {
					this.showFormErr(errors);
					if (!valid) return;
					const { cus_id, biz_id } = this.detail;
					const { area, bra_id, source_id, cus_mobile, dept_id, tag_name, ...args } =
						this.form;
					console.log("tag_name", tag_name, this.form);
					let form = {
						...args,
						cus_id,
						biz_id,
						bra_id,
						dept_id,
						channel_id: source_id,
						source_id,
						add_dept_id: dept_id,
						cus_area: area.join(","),
						tag_name: tag_name.join(","),
						cus_mobile: this.isEditMobile ? cus_mobile : "99" //特殊情况
					};
					form.province = area[0]; //省
					form.city = area[1]; //市
					form.area = area[2]; //区
					this.saving = true;
					await this.$service.customer.update(form).done(() => {
						this.saving = false;
					});
					this.$message.success("操作成功");
					this.$emit("confirm");
					this.close();
				});
			},
			//获取来源渠道
			async getSource() {
				const { biz_id } = this.detail;
				this.sourceList = [];
				if (!biz_id) return;
				const data = await this.$service.source.list({ biz_id });
				this.sourceList = data;
			},
			// 会员等级
			async getLevelList() {
				const { biz_id } = this.detail;
				await this.getBizRefLevel(biz_id);
			},
			async getTagList() {
				const { cus_id, biz_id } = this.detail;
				const res = await this.$service.customer.tag({
					cus_id,
					biz_id
				});
				this.tagList = res.lists;
			},
			// 获取部门
			async getDeptList() {
				const { biz_id } = this.form;
				this.deptList = [];
				if (!biz_id) return;
				const data = await this.$service.dept.list({
					parent_id: 0,
					is_store: 0,
					biz_id
				});
				this.deptList = delEmptyChildren(data);
			}
		}
	};
</script>
<style lang="scss" scoped>
    
	::v-deep {
		.el-dialog {
			height: auto;
			width: 400px;
			margin-top: 10vh;
			margin-bottom: 50px;
		}
		.el-col {
			min-height: 78px;
		}
		.el-form-item{
			 margin-bottom: 0px;
		}
	}

	.tag-wrap {
		width: 100%;
		height: 60px;

		::v-deep {
			.el-select__tags {
				top: 28%;
			}

			.el-input {
				height: 100%;
				background-color: #ffffff;
				border-radius: 4px;
				border: 1px solid #dcdfe6;

				&__inner {
					height: 28px !important;
					border: none;
				}
			}
		}
	}
</style>
